import * as React from 'react';
import microApp from '@micro-zoe/micro-app';
import { MicroAppConfig, setMicroAppInitFunction } from 'micro-app-tools/data';
import { sendDataUp, SubMicroAppInit } from 'micro-app-tools';
import { generateDataListener } from 'micro-app-tools/react18/index';
import MicroApp from 'micro-app-tools/react18/MicroApp';
import { SubAppSetting } from 'micro-app-tools/types';

const subAppSettingList = [
  {
    name: 'micromain',
    prefix: 'micromain',
    routerMode: 'history',
    urlMap: {
      localhost: 'http://127.0.0.1:1314/micromain/',
      test: 'https://micro-admin-template.lammu.cn/micromain/',
      pre: 'https://micro-admin-template.lammu.cn/micromain/',
      master: 'https://micro-admin-template.lammu.cn/micromain/',
    },
    builder: 'vite',
    iframe: true,
    framework: 'vue3',
  },
  {
    name: 'vue3',
    prefix: 'vue3',
    routerMode: 'hash',
    urlMap: {
      localhost: '//127.0.0.1:1320/vue3/',
      test: 'https://micro-admin-template.lammu.cn/vue3/',
      pre: 'https://micro-admin-template.lammu.cn/vue3/',
      master: 'https://micro-admin-template.lammu.cn/vue3/',
    },
    builder: 'vite',
    iframe: true,
    framework: 'vue3',
  },
  {
    name: 'vue2',
    prefix: 'vue2',
    routerMode: 'hash',
    urlMap: {
      localhost: '//127.0.0.1:1330/vue2/',
      test: 'https://micro-admin-template.lammu.cn/vue2/',
      pre: 'https://micro-admin-template.lammu.cn/vue2/',
      master: 'https://micro-admin-template.lammu.cn/vue2/',
    },
    builder: 'webpack',
    iframe: false,
    framework: 'vue2',
  },
  {
    name: 'react18',
    prefix: 'react18',
    routerMode: 'hash',
    urlMap: {
      localhost: '//127.0.0.1:1340/react18/',
      test: 'https://micro-admin-template.lammu.cn/react18/',
      pre: 'https://micro-admin-template.lammu.cn/react18/',
      master: 'https://micro-admin-template.lammu.cn/react18/',
    },
    builder: 'vite',
    iframe: true,
    framework: 'react18',
  },
  {
    name: 'vue2v',
    prefix: 'vue2v',
    routerMode: 'hash',
    urlMap: {
      localhost: '//127.0.0.1:1350/vue2v/',
      test: 'https://micro-admin-template.lammu.cn/vue2v/',
      pre: 'https://micro-admin-template.lammu.cn/vue2v/',
      master: 'https://micro-admin-template.lammu.cn/vue2v/',
    },
    builder: 'vite',
    iframe: true,
    framework: 'vue2',
  },
] as Array<SubAppSetting>;

MicroAppConfig.subAppSettingList = subAppSettingList;

setMicroAppInitFunction(() => {
  /** 初始化微前端配置 */
  SubMicroAppInit<'localhost' | 'test' | 'pre' | 'master'>({
    env: process.env.NODE_ENV === 'development' ? 'localhost' : 'master',
    tagName: 'micro-app-lowcode',
    dataListener: generateDataListener({
      /** 子应用接收到这个请求需要往上传递，直到传给顶部主应用 */
      micro_component_request: (data) => {
        sendDataUp({
          emitName: 'micro_component_request',
          parameters: [{
            ...data,
            subAppNameList: [...data.subAppNameList, window.__MICRO_APP_NAME__!]
          }],
        });
      },
      /** 子应用接收到这个请求需要往上传递，直到传给顶部主应用 */
      micro_component_destroy: (elementId) => {
        sendDataUp({
          emitName: 'micro_component_destroy',
          parameters: [elementId],
        });
      },
      /** 子应用接收到这个请求需要往上传递，直到传给顶部主应用 */
      micro_component_clear_props_slots: (elementId: string) => {
        sendDataUp({
          emitName: 'micro_component_clear_props_slots',
          parameters: [elementId],
        });
      },
    }),
    subAppSettingList: subAppSettingList,
  });

  /** 
   * 初始化子应用渲染环境（默认主应用/第一层子应用执行）
   */
  microApp.start({
    tagName: 'micro-app-lowcode',
    /** 防止子应用请求父应用资源（部署时需要配置这个url指向这个文件） */
    iframeSrc: `/micromain/empty.html`,
    'keep-router-state': true,
  });
})

export interface UseMicroAppProps {
  /**
   * 类型
   */
  type?: "primary" | "secondary" | "normal";
  url?: string;
  path?: string;
  style?: object;
  content?: string;
  slotcontent: React.FC
  __designMode?: 'design'
}

interface State {

}

/** 是否是阿里的在线url */
const isAliUrl = location.origin.includes('lowcode-engine.cn');

/**
 * 由于本地设计器(在线的没问题https://lowcode-engine.cn/demo/demo-basic-antd/index.html?debug)是webpack，使用MicroApp加载其它网站js会触发CSP规则导致报错
 * 所以本地设计时不渲染，本地预览使用vite项目来预览（admin项目或微前端主应用）
 */
class UseMicroApp extends React.Component<UseMicroAppProps, State> {
  render() {
    /** 是否处于编辑态（编辑态处于沙箱模式） */
    const isInDesignerMode = this.props.__designMode === 'design';

    return (
      <div>
        {
          this.props.url && this.props.path &&
          (
            (isInDesignerMode && !isAliUrl) ? <div style={{ backgroundColor: 'lightblue', padding: '10px' }}>MicroApp本地编辑态不可见</div> :
              // @ts-ignore
              <MicroApp _env="localhost" _name="micromain" _path="/demo/lottie" _defaultPage="/demo/lottie"/>
          )
        }
      </div>
    );
  }
}

export default UseMicroApp;


